<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #title="{ model, field }">
        <div v-html="model[field]" v-if="model[field]"></div>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema, defaultCodeList, defaultFlowList } from './viewList.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    getVisualColModify,
    getVisualColAdd,
    getVisualGetFormFieldsWithModuleRelated,
  } from '/@/api/module/module';

  export default defineComponent({
    name: 'ViewListDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      let dataRef = ref<any>({});
      const formCode = ref('');
      const moduleCode = ref('');
      const formFieldList = ref<Recordable[]>([]);
      const fieldsList = ref<Recordable[]>([]);
      const [
        registerForm,
        {
          resetFields,
          setFieldsValue,
          validate,
          updateSchema,
          removeSchemaByFiled,
          appendSchemaByField,
        },
      ] = useForm({
        labelWidth: 110,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        formCode.value = data?.formCode ?? '';
        moduleCode.value = data?.moduleCode ?? '';
        dataRef.value = {};
        if (unref(isUpdate)) {
          const record = data?.record;
          console.log('record', record);
          dataRef.value = {
            code: moduleCode.value,
            formCode: formCode.value,
            fieldName: record.field,
            fieldTitle: record.fieldTitle,
            title: record.title,
            fieldAlign: record.fieldAlign,
            fieldShow: record.show,
            fieldOrder: record.order,
            fieldWidth: record.width,
            fieldLink: record.link,
            fieldGroup: record.fieldGroup,
            fieldRowGroup: record.fieldRowGroup,
          };
          updateSchema([
            {
              field: 'fieldLink',
              ifShow: true,
            },
            {
              field: 'fieldTitle',
              ifShow: true,
            },
            {
              field: 'title',
              ifShow: true,
            },
          ]);
          await removeSchemaByFiled('fieldName');
          await appendSchemaByField(
            {
              field: 'fieldName',
              label: '字段',
              component: 'Select',
              defaultValue: 'ID',
              colProps: { span: 24 },
              render: ({ model, field }) => model[field],
            },
            undefined,
            true,
          );
        } else {
          dataRef.value = {
            code: moduleCode.value,
            formCode: formCode.value,
            fieldOrder: data?.dataSourceLength ? data.dataSourceLength + 1 : 1,
          };
          await getFormGetFieldsData();
          updateSchema([
            {
              field: 'fieldLink',
              ifShow: false,
            },
            {
              field: 'fieldTitle',
              ifShow: false,
            },
            {
              field: 'title',
              ifShow: false,
            },
          ]);
        }
        setFieldsValue({
          ...unref(dataRef),
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      async function handleSubmit() {
        try {
          const values = await validate();
          let formDate = Object.assign({}, unref(dataRef), values);
          setDrawerProps({ confirmLoading: true });
          console.log(formDate);
          if (unref(isUpdate)) {
            await getVisualColModify(formDate);
          } else {
            await getVisualColAdd(formDate);
          }
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      //获取数据
      const getFormGetFieldsData = async () => {
        formFieldList.value = [];
        try {
          if (!moduleCode.value) return;
          await getVisualGetFormFieldsWithModuleRelated({ moduleCode: moduleCode.value }).then(
            async (res) => {
              formFieldList.value = res || [];
              formFieldList.value.forEach((item: Recordable) => {
                item.label = item.name;
              });
              fieldsList.value = [...defaultCodeList, ...defaultFlowList, ...formFieldList.value];
              dataRef.value.fieldName = fieldsList.value[0].value;
              await removeSchemaByFiled('fieldName');
              await appendSchemaByField(
                {
                  field: 'fieldName',
                  label: '字段',
                  component: 'Select',
                  defaultValue: 'ID',
                  required: true,
                  colProps: { span: 24 },
                  componentProps: {
                    options: fieldsList.value,
                    showSearch: true,
                    optionFilterProp: 'label',
                  },
                },
                undefined,
                true,
              );
            },
          );
        } catch (err) {
          console.log('getFormGetFields', err);
        }
      };
      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
      };
    },
  });
</script>
